# -*- coding: UTF-8 -*-
from urllib import request
import  urllib
from datetime import datetime,date
import time
import  requests
from http.cookiejar import CookieJar
import re
global lst
class DaKa(object):
 def daka(self):
    lst = []
    cookie =CookieJar()
    handler = request.HTTPCookieProcessor(cookie)
    opener = request.build_opener(handler)
    # 登陆

    # 读取账号信息  位置信息
    f = open("info.txt",'r',encoding='UTF-8')
    for line in f:
        lst.append(line.strip())
        #print(line.strip())

    request.install_opener(opener)
    loginRequest = opener.open('http://portal.pku-hit.com/hospital/login/AjaxLogIn').read()
    values = {'username': lst[1], 'password': lst[2]}
    data =urllib.parse.urlencode(values)
    #print(data)
    loginRespone =opener.open('http://portal.pku-hit.com/hospital/login/AjaxLogIn?'+data)
    #print (loginRespone)
    # 认证
    renzhengResponse = opener.open(
        'http://portal.pku-hit.com/wx_api/oauth2_callback/beijing-BeiDaYiXinBI-18?redict_url=http://portal.pku-hit.com/oa/hr/apps/attendance/CardLocationJSNavigation?ssouserdid={userdid}').read();
    #print(renzhengResponse)
    pattern = re.compile(
        'http://portal.pku-hit\.com/oa/hr/apps/attendance/CardLocationJSNavigation\?ssouserdid=(.*?)\';')
    result = re.search(pattern, str(renzhengResponse,encoding='utf-8'))
    if result:
        opener.open(
            'http://portal.pku-hit.com/oa/hr/apps/attendance/CardLocationJSNavigation?ssouserdid=' + result.group(1))

        # 打卡

        values = {
            'province': lst[3],
            'city':lst[4],
            'district': lst[5],
            'adcode': lst[6],
            'addr': lst[7],
            'lat':lst[8],
            'lng':lst[9],
            'accuracy': '0',
            'dk_desc': ''
        }
        data = urllib.parse.urlencode(values)
        dakaRespone = opener.open('http://portal.pku-hit.com/oa/hr/apps/attendance/upLocationJS?'+data)
        print(str(datetime.now())+"打卡成功")
        #print (dakaRespone.read())
    else:
        print (values['username'] + ':登陆失败,未打卡')
 '''
判断是不是周一到周五
 '''
 def IsWorkDay(self):
     #读取日期
     dayOfWeek =datetime.now().weekday()

     if dayOfWeek>=0 and dayOfWeek<=4: #0到4 周一到周五
         return 0
     else:
         return 1
if __name__=='__main__':
    dakaClass = DaKa()
    lst=[]
    # 读取账号信息  位置信息
    f = open("info.txt", 'r', encoding='UTF-8')
    for line in f:
        lst.append(line.strip())
        #print(line.strip())
      #isWork=dakaClass.IsWorkDay()
    while True:
          now=datetime.now()
          dayOfWeek = now.weekday()
          if dayOfWeek>=0 and dayOfWeek<=4:
            if  (now.hour==int(lst[10]) and now.minute==int(lst[11])) or(now.hour==int(lst[12]) and now.minute==int(lst[13])):
               dakaClass.daka()
               print('suscess')

          # else:
          #     print(lst[12]+lst[13]+str(now.hour)+str(now.minute))
          time.sleep(60)
    #dakaClass.daka()


